package cn.itcast.health.mobile.controller;

import cn.itcast.health.commons.entity.Result;
import cn.itcast.health.commons.resources.MessageConstant;
import cn.itcast.health.commons.resources.RedisConstant;
import cn.itcast.health.commons.resources.RedisMessageConstant;
import cn.itcast.health.commons.sms.SMSUtils;
import cn.itcast.health.commons.sms.ValidateCodeUtils;
import cn.itcast.health.commons.utils.LogUtils;
import cn.itcast.health.interfaces.service.OrderService;
import cn.itcast.health.interfaces.service.SetmealService;
import cn.itcast.health.mobile.logs.OperationLog;
import cn.itcast.health.pojo.Member;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/orderMobile")
public class OrderMobileController {

    @Reference
    private SetmealService setmealService;

    //验证码需要存到redis里面去
    @Autowired
    private JedisPool jedisPool;


    @Reference(mock = "cn.itcast.health.mobile.Downgrade.orderServiceMock" ,timeout = 1500)
    private OrderService orderService;


    @GetMapping("/findByIdSetmealData.do")
    @OperationLog(moduleName = LogUtils.Module.MOBILE, operationType = LogUtils.Type.QUERY, operationContent = "移动端根据id查询套餐数")
    public Result findByIdSetmealData(@RequestParam("id") Integer id){
        Result result = setmealService.findByIdSetmealData(id);
        return result;
    }


    @PostMapping("/sendCodeToPhone.do")
    @OperationLog(moduleName = LogUtils.Module.MOBILE, operationType = LogUtils.Type.MODIFY, operationContent = "移动端审核手机号进行短信验证")
    public Result sendCodeToPhone(@RequestBody Map map){
        Result result = null;
        try {
            //获取手机号
            String telephone = (String) map.get("telephone");
            //获取验证码
            Integer integer = ValidateCodeUtils.generateValidateCode(6);
            //获取redis
            Jedis resource = jedisPool.getResource();

            //存手机号到redis
            resource.setex(telephone+"_"+ RedisMessageConstant.SENDTYPE_ORDER,60, String.valueOf(integer));
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone, String.valueOf(integer));
            System.out.println("验证码："+String.valueOf(integer));
            result = new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result(true, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        return result;
    }


    /**
     * 朱贺
     * @param map
     * @return
     */
    @RequestMapping(value = "/SendLoginVerifyCode.do",name = "发送图形验证码")
    @OperationLog(moduleName = LogUtils.Module.MOBILE, operationType = LogUtils.Type.QUERY, operationContent = "移动端验证图形验证码")
    public Result SendLoginVerifyCode(@RequestBody Map<String, String> map) {
        try {
            //输入的图形验证码
            String deviceId = map.get("deviceId");
            String imgCode = map.get("code");
            //从redis中获取图形验证码
            String redisImgCode = jedisPool.getResource().get(deviceId);
            if (null == redisImgCode || !redisImgCode.equals(imgCode)) {
                return new Result(false,"图形验证码输入错误");
            }
            return new Result(true, "图形验证码验证成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "图形验证码输入错误");
        }
    }

    /**
     * 无用处
     * @param map
     * @return
     */

//    @PostMapping("/validateCodeFromRedis.do")
//    public Result validateCodeFromRedis(@RequestBody Map map){
//        Result result = null;
//        try {
//            String code = (String) map.get("code");
//            String telephone = (String) map.get("telephone");
//            Jedis resource = jedisPool.getResource();
//            String codeFromRedis = resource.get(telephone + "_" + RedisMessageConstant.SENDTYPE_ORDER);
//            if(codeFromRedis == null || codeFromRedis.trim() == ""){
//                result =  new Result(false,"验证码过期");
//            }else {
//                //  验证码 有效期内  比对 验证码是否一致
//                if(code.equals(codeFromRedis)){
//                    result =  new Result(true, "恭喜您验证码正确");
//                }else{
//                    result =  new Result(false, MessageConstant.VALIDATECODE_ERROR);
//                }
//            }
//            resource.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            result = new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
//        }
//        return result;
//    }

    @PostMapping("/addOrderData.do")
    @OperationLog(moduleName = LogUtils.Module.MOBILE, operationType = LogUtils.Type.YUYUE, operationContent = "移动端根据用户手机号进行预约，注意预约信息成功与否是根据会员id，套餐id及预约时间三个参数统一来看的")
    public Result addOrderData(@RequestBody Map map){
        String id = String.valueOf(map.get("id"));
        if (id == null){
            String code = (String) map.get("code");
            String telephone = (String) map.get("telephone");
            Jedis resource = jedisPool.getResource();
            String codeFromRedis = resource.get(telephone + "_" + RedisMessageConstant.SENDTYPE_ORDER);
            if(codeFromRedis == null || codeFromRedis.trim() == ""){
               return new Result(false,"验证码过期");
            }else if(!code.equals(codeFromRedis)){
                //  验证码 有效期内  比对 验证码是否一致
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
        }
        Result result = orderService.addOrderData(map);
        if(result.isFlag()) {
            Map data = (Map) result.getData();
            Member member = (Member) data.get("member");
            jedisPool.getResource().set(member.getPhoneNumber() + "_" + RedisMessageConstant.SENDTYPE_USER, JSON.toJSONString(member));
        }
        return result;
    }
}
